package com.hrbxlh.actionImpl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.action.MemberAction;
import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.SessionValues;
import com.hrbxlh.util.pageUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hrbxlh.dao.MemberDao;
import com.hrbxlh.dao.NoticeDao;
import com.hrbxlh.dao.RelNotClaDao;
import com.hrbxlh.dao.RelStuClassDao;

@Component("noticeActionImpl")
@Transactional
public class NoticeActionImpl {

	@Resource(name = "noticeDao")
	private NoticeDao noticeDao;

	@Resource(name = "relNotClaDao")
	private RelNotClaDao relNotClaDao;

	@Resource(name = "relStuClassDao")
	private RelStuClassDao relStuClassDao;

	@Resource(name = "memberDao")
	private MemberDao memberDao;

	@Resource(name = "courseActionImpl")
	private CourseActionImpl courseActionImpl;

	//日志信息
	Logger logger = Logger.getLogger(NoticeActionImpl.class.getName());
	/**
	 * xzx
	 * @description 管理员设置消息信息
	 * @param 表单参数
	 * @param session
	 * @param response
	 *
	 * */
	public void addNotice(String jsonStr, HttpServletRequest request, HttpServletResponse res){
		ObjectMapper mapper = new ObjectMapper();
		//获取参数值
		Map<String,Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			if(paramMap.get("noticeContent") != null && !paramMap.get("noticeContent").equals("") && ((String) paramMap.get("noticeContent")).length() != 0){
				String[] resultArr = this.operateStrFunc(new String[] {(String) paramMap.get("noticeContent")});
				//返回参数
				paramMap.put("noticeContent", resultArr[0]);
				//判断用选的开始时间是否合理
				boolean flag = isTime(String.valueOf(paramMap.get("releaseTime")));
				if(!flag){
					courseActionImpl.responseStream(res, "{\"result\":\"error\",\"failMsg\":\"开始时间小于当前时间\"}");
				}else{
					//消息设置
					if(this.addNoticeUse(paramMap,request)){
						courseActionImpl.responseStream(res, "{\"result\":\"success\"}");
					}else{
						courseActionImpl.responseStream(res, "{\"result\":\"error\",\"failMsg\":\"消息设置失败\"}");
					}
				}

			}else{
				courseActionImpl.responseStream(res, "{\"result\":\"error\",\"failMsg\":\"请填写内容信息\"}");
			}
		} catch (Exception e) {
			e.printStackTrace();
			courseActionImpl.responseStream(res, "{\"result\":\"error\",\"failMsg\":\"systemError\"}");
		}
	}

	private boolean isTime(String releaseTime) throws ParseException {
		boolean flag = false;
		//转换为毫秒数
		Calendar c = Calendar.getInstance();
		//获取当前时间
		String timeStr = PubMethods.getNowTime(new Date(),2);
		c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(timeStr));
		long nowtime = c.getTimeInMillis();
		c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(releaseTime));
		long startime =  c.getTimeInMillis();
		if(nowtime<=startime){
			flag = true;
		}
		return flag;
	}

	/**
	 * @description 对用户的输入做去空格等操作
	 * @param inputArr需要做修改的字符数组
	 * */
	public String[] operateStrFunc(String[] inputArr){
		String[] strings = new String[inputArr.length];
		String use;
		for(int i = 0; i < inputArr.length; i++){
			use = inputArr[i];
			use = use.replaceAll("\n", "<br>");
			use = use.replaceAll("\r", "<br>");
			use = use.trim();
			strings[i] = use;
		}
		return strings;
	}

	/**
	 *xzx
	 *@description 设置消息信息管理员的
	 *@param 表单提交参数
	 *@param session
	 */
	public boolean addNoticeUse(Map<String,Object> paramMap,HttpServletRequest request) {
		try {
			paramMap.put("stuorteaId", new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg").get("stuorteaId"));
			//修改
			if(Integer.parseInt(paramMap.get("operateMark").toString()) == 1){
				noticeDao.updateNoticeSet(paramMap);
				return true;
				//添加
			}else{
				noticeDao.addNoticeSet(paramMap);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}



	/**
	 * 查询消息设置。
	 * @throws IOException
	 */
	public Map<String, Object> getNotice(HttpSession session,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> parameMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
//			String stuorteaId = "8888888";
			parameMap.put("stuorteaId", stuorteaId);
			Map<String, Object> noticeMap = noticeDao.getNotice(parameMap);
			returnMap.put("noticeMap", noticeMap);

			//通过教师号获取此教师所属班级(消息通知那---结课的班级不要)
			List<Map<String,Object>> classList = relStuClassDao.getClassByStuorteaIdAndNo(parameMap);
			returnMap.put("classList", classList);
			//通过教师号获取此教师基本信息
			List<Map<String, Object>> memberList =  memberDao.getMemberByStuorteaId(stuorteaId);
			returnMap.put("memberList", memberList);
			//通过消息主键获取此消息所有的班级
			if(noticeMap!=null){
				parameMap.put("noticeId", noticeMap.get("noticeId"));
			}
			List<String> noticeClassList = relNotClaDao.getClassByNoticeId(parameMap);
			returnMap.put("noticeClassList", noticeClassList);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * 通过noticeId查询消息设置。
	 * @throws IOException
	 */
	public Map<String, Object> getNoticeByNoticeId(Map<String, Object> parameMap,HttpSession session,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			parameMap.put("stuorteaId", stuorteaId);
			Map<String, Object> noticeMap = noticeDao.getNoticeByNoticeId(parameMap);
			returnMap.put("noticeMap", noticeMap);

			//通过教师号获取此教师所属班级(消息通知那---结课的班级不要)
			List<Map<String,Object>> classList = relStuClassDao.getClassByStuorteaIdAndNo(parameMap);
			returnMap.put("classList", classList);
			//通过教师号获取此教师基本信息
			List<Map<String, Object>> memberList =  memberDao.getMemberByStuorteaId(stuorteaId);
			returnMap.put("memberList", memberList);
			List<String> noticeClassList = relNotClaDao.getClassByNoticeId(parameMap);
			returnMap.put("noticeClassList", noticeClassList);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	/**
	 * 查询通过教师号获取此教师所属班级。
	 * @throws IOException
	 */
	public Map<String, Object> getNoticeNoClass(HttpSession session,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> parameMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			parameMap.put("stuorteaId", stuorteaId);
			//通过教师号获取此教师所属班级(消息通知那---结课的班级不要)
			List<Map<String,Object>> classList = relStuClassDao.getClassByStuorteaIdAndNo(parameMap);
			returnMap.put("classList", classList);
			//通过教师号获取此教师基本信息
			List<Map<String, Object>> memberList =  memberDao.getMemberByStuorteaId(stuorteaId);
			returnMap.put("memberList", memberList);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * 成绩设置。
	 * @throws IOException
	 */
	public Map<String,Object> addNoticeSet(Map<String,Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		boolean flag = false;
		boolean relFlag = false;
		boolean returnFlag = false;
		Map<String, Object> parameMap = new HashMap<String, Object>();
		String edit="";
		try {
			//做特殊字符校验
			if(PubMethods.isSpecialChar(String.valueOf(paramMap.get("noticeContent")))){
				returnFlag = false;
				logger.info("添加消息不可输入特殊字符");
				parameMap.put("returnFlag",returnFlag);
				parameMap.put("msg","添加消息不可输入特殊字符");
				return parameMap;
			}
			edit = (String) paramMap.get("noticeContent");
			if (paramMap.get("noticeContent")== null||paramMap.get("noticeContent").equals("")) {
				edit = "";
			} else if (edit.length() == 0) {
				edit = "";
			}
			edit = edit.replaceAll("\n", "<br>");
			edit = edit.replaceAll("\r", "<br>");
			paramMap.put("noticeContent", edit);
			//消息主键
			long noticeId = 0;
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			paramMap.put("stuorteaId", stuorteaId);
			//判断用选的开始时间是否合理
			returnFlag = isTime(String.valueOf(paramMap.get("releaseTime")));
			if(!returnFlag){
				parameMap.put("returnFlag",returnFlag);
				parameMap.put("msg","开始时间小于当前时间");
				return parameMap;
			}
			//去空格
			paramMap.put("noticeContent",String.valueOf(paramMap.get("noticeContent")).trim());
			if(Integer.parseInt(String.valueOf(paramMap.get("type")))==2){
				//通过noticeId修改
				//将已有的关联关系删除
				noticeId = Integer.parseInt(String.valueOf(paramMap.get("noticeId")));
				relStuClassDao.delRelnotClassByNoticeId(paramMap);
				flag = noticeDao.updateNoticeSet(paramMap);
			}if(Integer.parseInt(String.valueOf(paramMap.get("type")))==1){
				//添加
				flag = noticeDao.addNoticeSet(paramMap);
				noticeId = (Long) paramMap.get("noticeId");
			}
			if(flag){
				//添加消息与班级的关联表
				parameMap.put("noticeId", noticeId);
				List<Integer> classList = (List<Integer>) paramMap.get("classList");
				List<Map<String,Object>> parameList = new ArrayList<Map<String,Object>>();
				for(int i=0;i<classList.size();i++){
					Map<String,Object> classMap = new HashMap<String,Object>();
					classMap.put("noticeId", noticeId);
					classMap.put("classId", classList.get(i));
					parameList.add(classMap);
				}
				paramMap.put("parameList", parameList);
				relFlag = relNotClaDao.addRelNotCla(paramMap);
			}
			if(flag&&relFlag){
				returnFlag = true;
			}
			parameMap.put("returnFlag",returnFlag);
			parameMap.put("msg","");
		} catch (Exception e) {
			throw e;
		}
		return parameMap;
	}

	/**
	 * param noticeId
	 * 删除消息设置。
	 * @throws IOException
	 */
	@Transactional
	public boolean delNoticeSet(Map<String,Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {
		boolean relFlag = false;
		boolean returnFlag = false;
		boolean delFlag = false;
		try {
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId","roleId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId", stuorteaId);
			int roleId = Integer.parseInt(String.valueOf(sessionMap.get("roleId")));
			if (roleId!=3&&roleId!=4){
				//有数据做删除操作
				relFlag = relNotClaDao.delRelNotCla(paramMap);
			}else {
				relFlag = true;
			}

			if(relFlag){
				//删除原有消息
				delFlag = noticeDao.delNotice(paramMap);
			}
			if(delFlag&&relFlag){
				returnFlag = true;
			}
		} catch (Exception e) {
			throw e;
		}
		return returnFlag;
	}

	/**
	 * 查询消息设置。
	 * @throws IOException
	 */
	public Map<String, Object> getNoticeListByTeaId(Map<String, Object> parameMap,HttpSession session,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
		try {
			//获取分页数据
			int pageNow = (Integer)parameMap.get("pageNow");
			int pageSize = (Integer)parameMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			parameMap.put("startNum", startNum);
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			parameMap.put("stuorteaId", stuorteaId);
			list = noticeDao.getNoticeListByTeaId(parameMap);
			returnMap.put("noticeListByStu",list);
			//获取全部页数
			parameMap.put("pageNow", 0);
			List<Map<String, Object>> allNoticeList = noticeDao.getNoticeListByTeaId(parameMap);
			int totalPage = pageUtil.getTotalPage(allNoticeList, pageSize);
			returnMap.put("totalPage", totalPage);
			//查询当前学生所属教师集合
			/*List<Map<String,Object>> teaList = relStuClassDao.getStuTeaListByStuId(parameMap);
			//通过教师id集合获取消息集合
			if(teaList!=null&&teaList.size()!=0){
				parameMap.put("list", teaList);

			}
			//查询管理发的消息（所有人都可以看到）
			//查询管理员id
			List<Map<String,Object>>adminList = memberDao.getMemberMsgByRoleId();
			parameMap.put("list", adminList);
			List<Map<String,Object>> adminNoticeList = noticeDao.getNoticeListByTeaId(parameMap);
			//将两个集合合并
			list.addAll(adminNoticeList);*/
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * 同过人员id查询消息列表。
	 * @throws IOException
	 */
	public Map<String, Object> getNoticeListByAdminAndTeaId(Map<String,Object> parameMap, HttpSession session,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
		try {
			//获取分页数据
			int pageNow = (Integer)parameMap.get("pageNow");
			int pageSize = (Integer)parameMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			parameMap.put("startNum", startNum);
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			parameMap.put("stuorteaId", stuorteaId);
			List<Map<String, Object>> noticeList = noticeDao.getNoticeBysId(parameMap);
			returnMap.put("adminAndTeaNoticeList",noticeList);
			//获取全部页数
			parameMap.put("pageNow", 0);
			List<Map<String, Object>> allNoticeList = noticeDao.getNoticeBysId(parameMap);
			int totalPage = pageUtil.getTotalPage(allNoticeList, pageSize);
			returnMap.put("totalPage", totalPage);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
}
